#Stock.ema.12 
#35和69列，分别对应38和156股票
rm(list=ls())
#备份数据
save(list=ls(),file="data20131111")


#解压.csv数据
#z:\licaiData\index_csv\sh_index\
#for %a in (\licaiData\index_csv\sh_index\*.rar) do "C:\Program Files (x86)\WinRAR\Rar.exe" e %a 000001*.csv C:\R\data\000001\


#读入指数 csv数据
readcsv.no.filter<-function(path){
  #读取日内数据
  #path = "D:/SVN_code/R/script"; 
  path.old = getwd(1);
  setwd(path);
  files=dir(); #当前目录所有文件
  Stock<-list();
  #读取多个文件
  for(i in (1:length(files))){
    #for(i in (1:4)){  
    Stock.oneday<-try(read.csv(paste("",files[i],sep=''), stringsAsFactors=FALSE), silent=TRUE);  #读入CSV的时候不要将变量变成factor
    Stock.oneday<-Stock.oneday[,c(1,2,3,4,6,7,8,15,18)]; #提取0的列
    colnames(Stock.oneday)<-c("Market","symbol", "time","price","close.amount","close.pos","direction","buy1","sell1");
    Stock.date<-strsplit(Stock.oneday[1,3],' ')[[1]][1]; #提取日期
    Stock.oneday[,3]<-gsub(Stock.date,'',Stock.oneday[,3]);
    Stock[[Stock.date]] = Stock.oneday;
  }
  
  setwd(path.old); #返回原路径
  return(Stock);
}


#准备股票数据
data.pre <- function(Stock.intra.list, Stock.inter.list){  
  #获取日内数据
  Stock.symbol=Stock.intra$symbol[1];
  Stock.intra.his <<- Stock.intra[Stock.intra$date<"20051231",]; #将2005-12-31前的数据用来训练
  Stock.intra.test <<- Stock.intra[Stock.intra$date>="20051231",];
  
  #获取指数日内数据，只有2013年
  #idx.sz1.intra = readcsv.no.filter("000001");
  #View(idx.sz1.intra[c(1,2,3,4),]); #看非0的列
  
  #获取历史数据
  Stock.intra.his.date <<- unique(as.Date(as.character(Stock.intra.his$date),"%Y%m%d"));    #提取日内股票价格日期序列
  Stock.intra.his.list <<- split(Stock.intra.his,Stock.intra.his$date); #按照日期分割日内数据 
  
  #获取测试数据
  Stock.intra.test.date <<- unique(as.Date(as.character(Stock.intra.test$date),"%Y%m%d"));    #提取日内股票价格日期序列
  Stock.intra.test.list <<- split(Stock.intra.test,Stock.intra.test$date); #按照日期分割日内数据 
  
  Stock.inter.One.Stock = Stock.inter.list[[Stock.symbol]]; #选出该股票的日间数据
  Stock.inter.date = as.Date(as.character(Stock.inter.One.Stock$time),"%Y-%m-%d");    #提取日间股票价格日期序列
  
  #选取历史日间数据
  date.sel=match(Stock.intra.his.date, Stock.inter.date); #选出与日内数据日期匹配的行
  Stock.inter.his <<- Stock.inter.One.Stock[date.sel[!is.na(date.sel)],];
  
  #选取测试日间数据
  date.sel=match(Stock.intra.test.date, Stock.inter.date); #选出与日内数据日期匹配的行
  Stock.inter.test <<- Stock.inter.One.Stock[date.sel[!is.na(date.sel)],];
}

#处理历史股票数据得到统计波动幅度和宽度统计量
Stock.his.sta<-function(Stock.intra.his.date, Stock.intra.his.list){
  Stock.wave<-list();
  Stock.wave.all<-list();
  
  i=1
  Date.string= gsub('-','',as.character(Stock.intra.his.date[i])) #将Date格式转换为字符串格式
  Stock.wave= StatFun(Stock.intra.his.list[[Date.string]]$CLOSE);  
  Stock.wave.all = Stock.wave;
  
  for(i in 2:length(Stock.intra.his.date))
    #for(i in 1:2)
  {
    Date.string= gsub('-','',as.character(Stock.intra.his.date[i])) #将Date格式转换为字符串格式
    Stock.wave= StatFun(Stock.intra.his.list[[Date.string]]$CLOSE);  
    if(!is.na(Stock.wave$fluc.sd))
      Stock.wave.all = mapply(cbind, Stock.wave.all, Stock.wave, SIMPLIFY = FALSE);
  }
  
  #计算波动的统计特性，也可以考虑用其他方法，而不是正态分布拟合
  Stock.wave.fluc.mean<<-mean(Stock.wave.all$fluc.mean);
  Stock.wave.fluc.sd<<-mean(Stock.wave.all$fluc.sd); #日间波动
  Stock.wave.width.mean<<-mean(Stock.wave.all$width.mean);
  Stock.wave.width.sd<<-mean(Stock.wave.all$width.sd); #日间波动
  
  #绘图看一下，波动宽度和幅度的统计特性
  #hist(Stock.wave.all[,"Width"])
  #hist(Stock.wave.all[,"Fluc"])
  
  #设置正常条件和触发条件，是不是可以将波动率按照指数移动平均方式统计
  Norm.fluc = Stock.wave.fluc.mean+1*Stock.wave.fluc.sd; #正常股票波动量,2*delta
  Trig.fluc.pos  = Stock.wave.fluc.mean+1*Stock.wave.fluc.sd; #买入触发股票波动量,4*delta
  Trig.fluc.neg  = Stock.wave.fluc.mean-1*Stock.wave.fluc.sd; #卖出触发股票波动量,4*delta
  Norm.width = Stock.wave.width.mean+1*Stock.wave.width.sd; #正常股票波动量,2*delta
  Trig.width  = Stock.wave.width.mean+1*Stock.wave.width.sd; #触发股票波动量,4*delta
  
  Stock.his.sta <- list(Norm.fluc=Norm.fluc, Trig.fluc.pos=Trig.fluc.pos, Trig.fluc.neg=Trig.fluc.neg, Norm.width=Norm.width, Trig.width=Trig.width)
  return(Stock.his.sta)
}



###建立策略

#准备日间数据

read.idx()

#处理日内数据的波动
data.pre(Stock.intra2, Stock.inter.list)

idx.sta <- sta.idx(idx.intra.list) #统计指数历史波动
save(idx.sta, file="save/idx.sta")
idx.ema.12 <- ema.12(idx.sta)

#Stock.his.sta<-Stock.his.sta(Stock.intra.his.date, Stock.intra.his.list) #历史股票波动统计

read.stk()

source('../../script/sta.data.r')
Stock.sta.list <- sta.stock(Stock.intra.list) #准备股票历史波动
Stock.ema.12 <- ema.12(Stock.sta.list)
save(Stock.sta.list, Stock.ema.12, file="save/Stock.ema.12")

#测试日期列表
final.date = "2009-12-31"  
test.date = "2006-12-31"  
Stock.symbol = colnames(Stock.ema.12)
#Stock.intra.test.date = as.Date(names(Stock.intra.test.list), "%Y%m%d");

#生成交易信号，测试日期限制在2006年
buy.summary<-trade.signal(test.date, final.date, Stock.ema.12, Stock.inter.list, idx.inter, cash=100000)

#绘制一些图形
par(mfrow=c(1,1))
buy.bar = barplot(buy.summary$buy.signal)  #绘制买入/卖出的柱状图
lines(buy.summary$Stock.pos/2,col="blue")
plot(Stock.inter.test$CLOSE/max(Stock.inter.test$CLOSE),col="yellow") #归一化后的股票价格

#绘制一些图形
View(buy.summary)
par(mfrow=c(1,1))
Stock.inter.test.plot = Stock.inter.list[Stock.inter.test$time<final.date,];
regress = max(Stock.inter.test.plot$CLOSE)/(max(buy.summary$equity.all)/100000)
plot(buy.summary$equity.cash/100000, type='l',col="orange")
lines(Stock.inter.test.plot$CLOSE/regress,col="brown")  #绘制买入/卖出的柱状图
lines(buy.summary$Stock.pos/2,col="blue")

plot(Stock.inter.list[[4]]$CLOSE)
axis(1, Stock.inter.list[[4]]$time)

plot(Stock.ema.12$fluc.mean, type='l',col="orange")

par(mfrow=c(2,1))
plot(Stock.inter.test.plot$CLOSE/max(Stock.inter.test.plot$CLOSE), type='l',col="orange", main="Stock price")
lines(buy.summary$Stock.fluc.mean/max(buy.summary$Stock.fluc.mean), type='h',col="brown", main="Stock intra fluc")  #绘制买入/卖出的柱状图
plot(buy.summary$idx.fluc.mean/max(buy.summary$idx.fluc.mean), type='h',col="blue",  main="idx intra fluc")

#根据信号强弱选择持有天数，固定持有一定天数
#为何在400日左右的上涨未被检测到

#无法处理震荡下跌情况
#复权因子